package com.gl.goods.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;

import com.gl.goods.R;
import com.gl.goods.widght.LoadingDialog;
import com.gl.goods.widght.LoadingLayout;
import com.gl.library.tool.RxSPTool;
import com.gl.library.utils.StringUtils;

import org.simple.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Fragment基类
 * Created by wangwc on 2016/12/14.
 */
public abstract class BaseFragment extends Fragment {

    protected LayoutInflater mInflater;
    protected Activity mContext;
    private Unbinder mBinder;
    private View mBaseView;
    private LinearLayout mLlRootLayout;
    private LoadingLayout mLoadingLayout;
    private LoadingDialog mLoadingDialog;
    protected boolean isInit = false;
	/**
     * 当前Fragment是否在显示标示
     */
    protected boolean isVisible = false;
    private long lastClickTime;
    public int memberId;
    public String loginToken;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = (Activity)context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.mInflater = inflater;
        if (mBaseView == null) {
            if (initLayout() != 0) {
                mBaseView = inflater.inflate(R.layout.fragment_base, container, false);
                View view = inflater.inflate(initLayout(), container, false);
                mLlRootLayout = (LinearLayout) mBaseView.findViewById(R.id.ll_root_layout);
                mLoadingLayout = (LoadingLayout) mBaseView.findViewById(R.id.view_loading);
                mLlRootLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                // 错误页面的点击按钮操作
                mLoadingLayout.setOnActionPositiveListener(new LoadingLayout.OnActionPositiveListener() {
                    @Override
                    public void onActionPositive() {
                        onActionPositiveClick();
                    }
                });

                mLoadingLayout.setOnActionNegativeListener(new LoadingLayout.OnActionNegativeListener() {
                    @Override
                    public void onActionNegative() {
                        onActionNegativeClick();
                    }
                });
            }
            if (MyApplication.getInstance().isLogin()){
                memberId = RxSPTool.getInt(mContext, "memberId");
                loginToken = RxSPTool.getString(mContext,"token");
            }else {
                memberId = -1;
                loginToken = "";
            }
            // 注册依赖注入对象
            mBinder = ButterKnife.bind(this, mBaseView);

            // 注册事件总线对象
            EventBus.getDefault().register(this);

            initView(savedInstanceState, mBaseView);
            initData();
        }

        isVisible = getUserVisibleHint(); // 初始化设置Fragment是否在显示
        isInit = true;
        return mBaseView;
    }

    // 此方法针对ViewPager使用FragmentPagerAdapter的Fragment有效
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 判断当前Fragment是否在显示
        if(isVisibleToUser) {
            isVisible = true;
        } else {
            isVisible = false;
        }
        if (!isInit) {
            return;
        }
        if (isVisibleToUser) {
            onLazyLoad();
        }
    }

    // 此方法针对show和hide的Fragment有效
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden == false) {
            isVisible = true;
            onLazyLoad();
        } else {
            isVisible = false;
        }
    }

    // 判断是否登录
//    protected boolean isLogin() {
//        String token = SharedPrefUtil.getValue(mContext, WjbConstants.SP_TOKEN_DATA, null);
//        return token != null ? true : false;
//    }

    protected abstract int initLayout();

    protected abstract void initView(Bundle savedInstanceState, View view);

    protected void initData() {}


    // Fragment懒加载数据方法
    protected void onLazyLoad() {}

    protected void onActionNegativeClick() {}

    protected void onActionPositiveClick() {}

    public void showDialogLoading(@StringRes int resId) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(mContext, resId);
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public void hideDialogLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
    }

    public void showLoadingView(String text) {
        mLoadingLayout.setLoadingText(text);
        mLlRootLayout.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.LOADING);
    }

    public void showDataView() {
        mLlRootLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setVisibility(View.GONE);
        mLoadingLayout.setStatue(LoadingLayout.GONE);
    }

    public void showDefaultNoData(String errMsg) {
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_DATA);
        if (StringUtils.isNotEmpty(errMsg)) {
            mLoadingLayout.setErrorInfo(errMsg);
        }
    }

    public void showDefaultNoData(String errMsg, int resId) {
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_DATA);
        mLoadingLayout.setErrorInfo(errMsg, resId);
    }

    public void showNoDataView(String contextText, int contextResId, String positiveText) {
        showNoDataView(contextText, contextResId, null, positiveText);
    }

    public void showNoDataView(String contextText, int contextResId, String negativeText, String positiveText) {
        mLoadingLayout.setErrorInfo(contextText, contextResId);
        mLoadingLayout.setActionNegativeButton(negativeText);
        mLoadingLayout.setActionPositiveButton(positiveText);
        mLlRootLayout.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_DATA);
    }

    public void showNoNetWorkView() {
        mLoadingLayout.setErrorInfo("网络错误", R.mipmap.ic_launcher);
        mLlRootLayout.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_NETWORK);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();

    }
    /**
     * 判断Activity是否Destroy
     *
     * @param mActivity
     * @return
     */
    public static boolean isDestroy(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;

        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        hideDialogLoading();
        // 注销事件总线对象
        EventBus.getDefault().unregister(this);
        // 注销依赖注入对象
        mBinder.unbind();
    }
    public void goTo(Class<? extends Activity> des) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), des);
        startActivity(intent);
    }

    public void goTo(Class<? extends Activity> des, Intent intent) {
        intent.setClass(getActivity(), des);
        startActivity(intent);
    }

    /**
     * [防止快速点击]
     *
     * @return
     */
    private boolean isFastClick() {
        boolean flag = false;

        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= 1000) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyBoard(Activity activity) {
        if (activity == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(activity.getWindow().peekDecorView()
                    .getWindowToken(), 0);
        }
    }

    /** 校验是否登录 */
//    public boolean checkLogin() {
//        String sessionId = SharedPrefUtil.getValue(getActivity(), WjbConstants.SP_TOKEN_DATA, null);
//        if (WjbStringUtils.isEmpty(sessionId)) {
//            return false;
//        }
//        return true;
//    }

}
